package tbc.text2;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import top.njclearn.test.Web;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ServerMonitor {
    int num;
    /**
     * 将任务在线程池中运行，每一次检测结束重新读取文件中的服务器地址
     */
    public void run() {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(1,
                1,
                1000,
                TimeUnit.MICROSECONDS,
                new LinkedBlockingDeque<>());
        for (int j = 0; j < 100; j++) {
            pool.submit(new Thread(() -> {
                List<Web> list = inPut();
                System.out.println("===========================");
                System.out.println("第" + (++num) + "次运行");
                for (int i = 0; i < list.size(); i++) {
                    boolean check = check(list.get(i).getWeb(), i);
                    if (check) {
                        System.out.println("上传成功");
                    } else {
                        System.err.println("上传失败，服务器的管理员邮箱为： " + list.get(i).getManagerEmail());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }));
//        pool.shutdown();
        }
    }

    /**
     * 发送请求，检测服务器是否正常
     * 如果服务器正常，为每个服务器发送文件
     * 如果异常，返回异常码
     *
     * @param s
     * @param i
     */
    private boolean check(String s, int i) {
        try {
            long startTime = System.currentTimeMillis();
            URL url = new URL("http://" + s);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            String requestMethod = connection.getRequestMethod();
//            System.out.println(requestMethod);        // get
            int responseCode = connection.getResponseCode();
            long endTime = System.currentTimeMillis();
            if (responseCode == 200) {
                System.out.println("服务器 " + s + " 服务正常" + " 请求时间： " + (endTime - startTime) + "毫秒");
                boolean push = push(i);
                if (push) {
                    return true;
                } else {
                    return false;
                }
            } else {
                System.err.println("服务器 " + s + " 服务出现异常 " + " 异常码： " + responseCode);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    /**
     * JSON文件使用相对地址
     * 将文件中的服务器地址转化为Web对象存储在list集合中
     *
     * @return list
     */
    public static List<Web> inPut() {
        try (FileReader reader = new FileReader("src/tbc/text2/server.json")) {
            String str = "";
            int a = 0;
            while ((a = reader.read()) != -1) {
                str += (char) a;
            }
            List<Web> list = JSON.parseArray(str, Web.class);
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将文件上传至服务器
     *
     * @param i
     * @return
     */
    private boolean push(int i) {
        int port = 21;
        String username = "test";
        String password = "12345678";
        FTPClient ftpClient = new FTPClient();
        List<Web> list = inPut();

        String server = list.get(i).getWeb();
        // 获取本地要上传的文件
        File firstLocalFile = new File("resource/logs/error.log");
        try (InputStream in = new FileInputStream(firstLocalFile);) {
            // 连接到FTP服务器
            ftpClient.connect(server, port);
            // 登录
            ftpClient.login(username, password);
            // 设置为被动模式
            ftpClient.enterLocalPassiveMode();
            // 设置文件类型为二进制（防止乱码）
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // 上传文件
            System.out.println("开始上传文件： " + firstLocalFile.getName());
            ftpClient.changeWorkingDirectory("/www/wwwroot/test");
            String firstRemoteFile =System.currentTimeMillis()+ ".log";

            boolean done = ftpClient.storeFile(firstRemoteFile, in);
            if (done) {
                return true;
            }
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return false;
    }

}